import logging
import os

from PyQt5.QtCore import QObject, pyqtSignal

from app_config import AppConfig

class QTextLogSignal(QObject):
    new_log = pyqtSignal(str)

class QtLogHandler(logging.Handler):
    def __init__(self, tb_log_widget):
        super().__init__()
        self.tb_log_widget = tb_log_widget
        self.signal = QTextLogSignal()
        self.signal.new_log.connect(self.append_to_log)

    def emit(self, record):
        msg = self.format(record)
        self.signal.new_log.emit(msg)

    def append_to_log(self, msg):
        self.tb_log_widget.append(msg)
        self.tb_log_widget.verticalScrollBar().setValue(
            self.tb_log_widget.verticalScrollBar().maximum()
        )

class Logger:
    _instance = None

    def __new__(cls, tb_log_widget=None, log_name=AppConfig.Log.LOG_NAME, log_dir=AppConfig.Log.LOG_DIR):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._init_logger(tb_log_widget, log_name, log_dir)
        return cls._instance

    def _init_logger(self, tb_log_widget, log_name, log_dir):
        os.makedirs(log_dir, exist_ok=True)
        log_file = AppConfig.Path.LOG_FILE

        self.logger = logging.getLogger(log_name)
        self.logger.setLevel(logging.DEBUG)

        if not self.logger.handlers:
            formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')

            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setFormatter(formatter)
            self.logger.addHandler(file_handler)

            if tb_log_widget:
                qt_handler = QtLogHandler(tb_log_widget)
                qt_handler.setFormatter(formatter)
                self.logger.addHandler(qt_handler)

    def get_logger(self):
        return self.logger
